﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FytSoa.Common;
using FytSoa.Core.Model.Sw;
using FytSoa.Service.Interfaces;
namespace FytSoa.Service.Implements
{
    /*!
    * 文件名称：Sw_coupon服务接口实现
    */
    public class Sw_couponService : BaseServer<Sw_coupon>, ISw_couponService
    {
        /// <summary>
        /// 添加一条数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> Add(Sw_coupon model)
        {
            var res = new ApiResult<string>() {  statusCode=(int)ApiEnum.Error};
            try
            {
                model.Guid = Guid.NewGuid().ToString();
                //根据数量创建优惠券
                var list = new List<Sw_couponlog>();
                for (int i = 0; i < model.Amount; i++)
                {
                    list.Add(new Sw_couponlog() {
                        Guid= Guid.NewGuid().ToString(),
                        CouponGuid=model.Guid,
                        Number=(model.CouponTypes==1?"GW":"YF")+Utils.Number(15)
                    });
                }
                var asyncResult =await Db.Ado.UseTranAsync(() =>
                {
                    Db.Insertable(model).ExecuteCommand();
                    Db.Insertable(list).ExecuteCommand();
                });
                if (asyncResult.IsSuccess) {
                    res.statusCode = (int)ApiEnum.Status;
                }
                else
                {
                    res.message = asyncResult.ErrorMessage;
                }
                
            }
            catch (Exception ex)
            {
                res.message = ex.Message;
            }
            return res;
        }
    }
}